package com.lcc.generate.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.lcc.generate.Config;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidPool {

	private DruidPool() {}

	/**
	 * 1、导入druid包
	 * 2、配置druid.properties文件
	 * 3、加载配置文件
	 * 4、通过工厂获得连接池对象 ds = DruidDataSourceFactory.createDataSource(prop);
	 * 5、获取连接对象ds.getConnection()
	 * 6、归还连接对象，调用close()
	 */
	private static DataSource ds;

	public static void init(Config config) {
		Properties prop = new Properties();
		try {
			prop.setProperty("driver", config.dbDriver);
			prop.setProperty("url", config.dbUrl);
			prop.setProperty("username", config.dbUsername);
			prop.setProperty("password", config.dbPassword);
			ds = DruidDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 释放连接对象
	 * @param connection	数据库连接对象
	 */
	public static void close(Connection connection) {
		close(connection, null, null);
	}
	/**
	 * 释放连接对象和sql执行对象
	 * @param connection	数据库连接对象
	 */
	public static void close(Connection connection,Statement statement) {
		close(connection, statement, null);;
	}
	/**
	 * 释放资源
	 * @param connection	连接对象
	 * @param statement		语句执行对象
	 * @param resultSet		结果集对象
	 */
	public static void close(Connection connection,Statement statement,ResultSet resultSet){
		if(resultSet!=null)
			try {
				resultSet.close();} 
			catch (SQLException e) {
				e.printStackTrace();
			}
		if(statement!=null)
			try {
				statement.close();} 
			catch (SQLException e) {
				e.printStackTrace();
			}
		if(connection!=null)
			try {
				connection.close();} 
			catch (SQLException e) {
				e.printStackTrace();
			}
	}
	/**
	 * 获得连接池
	 * @return
	 */
	public static DataSource getDs() {
		return ds;
	}
	
}
